
var TextEditor = function() {
  this.t = ''
  this.c = 0
};

/** 
 * @param {string} text
 * @return {void}
 */
TextEditor.prototype.addText = function(text) {
  let c = this.c, t = this.t
  if(t.length === 0) {
    this.t = text
    this.c = text.length-1
    return
  } else if(c === -1) {
    this.t = text + this.t
    this.c += text.length
    return
  }
  const a = t.split('')
  a[c] += text
  this.t = a.join('')
  this.c += text.length
  // console.log('add', this.t, this.c)
};

/** 
 * @param {number} k
 * @return {number}
 */
TextEditor.prototype.deleteText = function(k) {
  if(this.t.length === 0 || this.c === -1) return 0
  let c = this.c, t = this.t
  const a = t.split('')
  let cnt = 0
  for(let i = 0; i<k; i++) {
    if(c === -1) break
    a[c] = ''
    cnt++
    c--
  }
  this.t = a.join('')
  this.c = this.c - cnt
  // console.log('delete', this.t, this.c)
  return cnt
};

/** 
 * @param {number} k
 * @return {string}
 */
TextEditor.prototype.cursorLeft = function(k) {
  if(this.c === -1 || this.t.length === 0) return ''
  let c = this.c, t = this.t
  for(let i = 0; i<k; i++) {
    if(c === -1) break
    c--
  }
  this.c = c
  if(c === -1) return ''
  // console.log('left', this.t, this.c)
  let s = ''
  for(let i = 0; i<10; i++) {
    if(c === -1) break
    s = t[c] + s
    c--
  }
  return s
};

/** 
 * @param {number} k
 * @return {string}
 */
TextEditor.prototype.cursorRight = function(k) {
  if(this.t.length === 0) return ''
  let c = this.c, t = this.t
  for(let i = 0; i<k; i++) {
    if(c === t.length-1) break
    c++
  }
  this.c = c
  // console.log('right', t, this.c)
  let s = ''
  for(let i = 0; i<10; i++) {
    if(c === -1) break
    s = t[c] + s
    c--
  }
  return s
};

/**
 * Your TextEditor object will be instantiated and called as such:
 * var obj = new TextEditor()
 * obj.addText(text)
 * var param_2 = obj.deleteText(k)
 * var param_3 = obj.cursorLeft(k)
 * var param_4 = obj.cursorRight(k)
 */

//[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]